package system

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"jgyApi/server/global"
	systemReq "jgyApi/server/model/system/request"
	systemRes "jgyApi/server/model/system/response"
	"jgyApi/server/utils"
	"net/http"
	"sync"
	"time"
)

type GanKaoService struct{}

func (ganKaoService *GanKaoService) ActiveUser(req *systemReq.ActiveUserReq) (res *systemRes.ActiveUseRes, err error) {
	sercret := global.GVA_CONFIG.System.GanKaoSecret
	tokenStr := fmt.Sprintf("%s%d%d%d%s%s", req.AppID, req.IsTeacher, req.SpecificationID, req.Timestamp, req.UID, sercret)
	tokenStr = utils.MD5V([]byte(tokenStr))
	urlPath := fmt.Sprintf("https://www.gankao.com/api/service/activeUser?isteacher=%d&uid=%s&app_id=%s&timestamp=%d&specification_id=%d&token=%s",req.IsTeacher, req.UID, req.AppID, req.Timestamp, req.SpecificationID, tokenStr)
	r, err := http.Get(urlPath)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, fmt.Errorf("请求赶考地址失败")
	}
	defer r.Body.Close()
	b, err2 := ioutil.ReadAll(r.Body)
	if err2 != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, fmt.Errorf("解析赶考返回内容失败")
	}
	var ganKaoRes systemRes.ActiveUseRes
	err = json.Unmarshal(b, &ganKaoRes)
	if err != nil {
		global.GVA_LOG.Error(err.Error())
		return nil, fmt.Errorf("解析赶考返回值失败失败")
	}
	if ganKaoRes.Code != 10000 {
		return nil, fmt.Errorf(ganKaoRes.Msg)
	}
	return &ganKaoRes, nil
}

func (ganKaoService *GanKaoService) CreateUser(req *systemReq.CreateUserReq) (res *systemRes.CreateUseRes, err error) {
	sercret := global.GVA_CONFIG.System.GanKaoSecret
	tokenStr := fmt.Sprintf("%s%d%s%s", req.AppID, req.Timestamp, req.UID, sercret)
	tokenStr = utils.MD5V([]byte(tokenStr))
	urlPath := fmt.Sprintf("https://www.gankao.com/api/service/createUser?uid=%s&app_id=%s&timestamp=%d&token=%s", req.UID, req.AppID, req.Timestamp, tokenStr)
	r, err := http.Get(urlPath)
	if err != nil {
		return nil, fmt.Errorf("请求赶考地址失败")
	}
	defer r.Body.Close()
	b, err2 := ioutil.ReadAll(r.Body)
	if err2 != nil {
		return nil, fmt.Errorf("解析赶考返回内容失败")
	}
	var ganKaoRes systemRes.CreateUseRes
	err = json.Unmarshal(b, &ganKaoRes)
	if err != nil {
		return nil, err
	}
	if ganKaoRes.Code != 10002 {
		return nil, fmt.Errorf(ganKaoRes.Msg)
	}
	return &ganKaoRes, nil
}

//
// TestConsuming
//  @Description: 消费队列
//
func TestConsuming() {
	redisConn := global.GVA_REDIS
	conn := context.Background()
	pool, err := NewPool(20)
	if err != nil {
		panic(err)
	}
	wg := new(sync.WaitGroup)

	c := time.Tick(1 * time.Second)
	info := DelayInfo{
		JobPoolKey: "active_pool_key_",
		BaseDelayBucketKey: "active_delay_bucket",
		BaseReadyQueueKey: "active_ready_queue",
		DelayAddTime: 100,
	}

	for next := range c {
		//fmt.Println("我在执行了")
		err := TimerDelayBucket(redisConn, conn, pool, wg,info)
		if err != nil {
			fmt.Println("定时timer发生错误：", next, err)
		}
	}
	wg.Wait()
	pool.Close()
}
